import React, { useState, useEffect } from 'react';
import { Typography, Statistic, Row, Col, Card, Space, Input, Select, Divider, message, Button, Tag, List, Avatar, Carousel, Alert, Progress, Badge, Tooltip } from 'antd';
import { SearchOutlined, RocketOutlined, GlobalOutlined, TeamOutlined, DatabaseOutlined, StarOutlined, TrophyOutlined, FireOutlined, CloudUploadOutlined, DownloadOutlined, GiftOutlined, UserOutlined, PlusOutlined, EyeOutlined, LikeOutlined, CommentOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import TorrentList from '../components/TorrentList/TorrentList';
import { torrents, users, auth, topics, broadcasts, categories, points } from '../services';
import { getUser } from '../utils/localStorage';

const { Title, Text, Paragraph } = Typography;
const { Search } = Input;
const { Option } = Select;

const Home = () => {
  const navigate = useNavigate();
  const [torrentsList, setTorrentsList] = useState([]);
  const [user, setUser] = useState(null);
  const [userStats, setUserStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [messageApi, contextHolder] = message.useMessage();
  const [recentTorrents, setRecentTorrents] = useState([]);
  const [hotTopics, setHotTopics] = useState([]);
  const [latestBroadcasts, setLatestBroadcasts] = useState([]);
  const [categoriesData, setCategoriesData] = useState([]);
  const [userPoints, setUserPoints] = useState(null);
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    loadHomeData();
  }, []);

  const loadHomeData = async () => {
    try {
      setLoading(true);

      // 获取当前用户
      const user = JSON.parse(localStorage.getItem('starrypt_user') || 'null');
      setCurrentUser(user);

      // 获取用户信息
      const currentUser = getUser();
      setUser(currentUser);

      // 获取用户统计数据
      try {
        const statsResponse = await users.getUserStats();
        if (statsResponse.success) {
          setUserStats(statsResponse.data);
        }
      } catch (error) {
        console.error('获取用户统计数据失败:', error);
      }

      // 获取种子列表 - 优先使用OSS接口获取所有种子
      let torrentResponse = null;
      try {
        const ossResponse = await torrents.getAllUploadedTorrents();
        if (ossResponse.success) {
          // 适配OSS种子数据字段到前端期望格式
          const adaptedTorrents = (ossResponse.data.torrents || []).map((torrent, index) => ({
            ...torrent,
            id: torrent.id || torrent.hash || `torrent_${index}`,
            name: torrent.name || '未命名种子',
            category: torrent.classification || '未分类', // 显示用的分类字段
            classification: torrent.classification || '未分类', // 保留原始字段用于筛选
            // 处理促销类型：后端category字段表示促销类型，null表示无促销
            promotion: torrent.category && torrent.category !== null ? torrent.category : 'none',
            uploadTime: torrent.fileTimestamps || torrent.uploadTime || new Date().toISOString(),
            seeders: torrent.seeder || 0,
            downloads: torrent.download || 0,
            uploader: torrent.uploader || '匿名用户'
          }));

          setTorrentsList(adaptedTorrents);
          torrentResponse = ossResponse;
        } else {
          // 如果OSS接口失败，回退到原来的接口
          const response = await torrents.getTorrents();
          if (response.success) {
            setTorrentsList(response.data.torrents || []);
            torrentResponse = response;
          } else {
            messageApi.error('加载种子失败');
          }
        }
      } catch (error) {
        console.warn('OSS接口失败，尝试使用备用接口:', error);
        try {
          const response = await torrents.getTorrents();
          if (response.success) {
            setTorrentsList(response.data.torrents || []);
            torrentResponse = response;
          } else {
            messageApi.error('加载种子失败');
          }
        } catch (backupError) {
          messageApi.error('加载种子失败');
        }
      }

      // 并行加载所有数据
      const [topicsRes, broadcastsRes] = await Promise.all([
        topics.getTopics(),
        broadcasts.getBroadcasts()
      ]);

      // 处理种子数据
      if (torrentResponse && torrentResponse.success) {
        const rawTorrents = torrentResponse.data.torrents || [];
        console.log('🔍 原始种子数据示例:', rawTorrents[0]);

        // 适配OSS种子数据字段到前端期望格式
        const adaptedTorrents = rawTorrents.map((torrent, index) => ({
          ...torrent,
          // 统一字段映射 - 确保ID字段存在且有效
          id: torrent.id || torrent.hash || `torrent_${index}`,
          name: torrent.name || '未命名种子',
          title: torrent.name || '未命名种子',
          category: torrent.classification || '未分类', // 显示用的分类字段
          classification: torrent.classification || '未分类', // 保留原始字段用于筛选
          size: torrent.size || 0,
          seeders: torrent.seeder || 0,
          leechers: 0, // OSS数据没有leechers
          downloads: torrent.download || 0,
          likes: torrent.upvote || 0,
          views: torrent.watchs || 0,
          // 处理促销类型：后端category字段表示促销类型，null表示无促销
          promotion: torrent.category && torrent.category !== null ? torrent.category : 'none',
          uploadTime: torrent.fileTimestamps || torrent.uploadTime || new Date().toISOString(),
          uploadDate: torrent.fileTimestamps || torrent.uploadTime || new Date().toISOString(),
          uploader: torrent.uploader || '匿名用户',
          qualityScore: Math.floor(Math.random() * 100) + 50 // 随机质量分数
        }));

        console.log('✅ 适配后的种子数据示例:', adaptedTorrents[0]);

        // 按上传时间排序并取前6个
        const sortedTorrents = adaptedTorrents
          .sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
          .slice(0, 6);

        console.log('📋 最新种子列表:', sortedTorrents.map(t => ({
          name: t.name,
          uploadTime: t.uploadTime,
          size: t.size,
          category: t.category
        })));

        setRecentTorrents(sortedTorrents);
      }

      // 处理话题数据
      if (topicsRes.success) {
        const topicsData = topicsRes.data.topics || [];

        // 为每个话题计算实际的帖子数量
        const topicsWithRealPostCount = await Promise.all(
          topicsData.map(async (topic) => {
            try {
              // 获取该话题的实际帖子数量
              const postsRes = await topics.getTopicPosts(topic.topicId || topic.id);
              const realPostCount = postsRes.success ? (postsRes.data.total || postsRes.data.posts?.length || 0) : topic.postCount || 0;

              return {
                ...topic,
                postCount: realPostCount
              };
            } catch (error) {
              console.warn(`获取话题 ${topic.topicId || topic.id} 帖子数量失败:`, error);
              return topic; // 使用原始数据
            }
          })
        );

        // 按热度排序并取前4个
        const sortedTopics = topicsWithRealPostCount
          .sort((a, b) => (b.memberCount + b.postCount * 2) - (a.memberCount + a.postCount * 2))
          .slice(0, 4);

        setHotTopics(sortedTopics);
        console.log('🔥 热门话题数据:', sortedTopics);
      }

      // 处理广播数据
      if (broadcastsRes.success) {
        const sortedBroadcasts = (broadcastsRes.data.broadcasts || [])
          .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          .slice(0, 5);
        setLatestBroadcasts(sortedBroadcasts);
      }

      // 处理分区数据 - 基于实际种子数据计算分区统计
      if (torrentResponse && torrentResponse.success) {
        const rawTorrents = torrentResponse.data.torrents || [];

        // 适配种子数据字段用于分区统计
        const adaptedTorrentsForCategories = rawTorrents.map(torrent => ({
          ...torrent,
          category: torrent.classification || '未分类', // 使用classification作为分类
          classification: torrent.classification || '未分类' // 保留原始字段
        }));

        // 定义分区及其颜色
        const predefinedCategories = [
          { name: '电影', color: '#1890ff' },
          { name: '电视剧', color: '#52c41a' },
          { name: '动漫', color: '#722ed1' },
          { name: '音乐', color: '#fa8c16' },
          { name: '游戏', color: '#eb2f96' },
          { name: '软件', color: '#13c2c2' },
          { name: '图书', color: '#faad14' },
          { name: '纪录片', color: '#f5222d' }
        ];

        // 统计每个分区的资源数量
        const categoryStats = predefinedCategories.map(category => {
          const resourceCount = adaptedTorrentsForCategories.filter(torrent =>
            torrent.category === category.name
          ).length;

          return {
            ...category,
            resourceCount
          };
        });

        console.log('📊 分区统计数据:', categoryStats);
        setCategoriesData(categoryStats);
      } else {
        // 如果没有种子数据，显示默认分区
        const defaultCategories = [
          { name: '电影', color: '#1890ff', resourceCount: 0 },
          { name: '电视剧', color: '#52c41a', resourceCount: 0 },
          { name: '动漫', color: '#722ed1', resourceCount: 0 },
          { name: '音乐', color: '#fa8c16', resourceCount: 0 },
          { name: '游戏', color: '#eb2f96', resourceCount: 0 },
          { name: '软件', color: '#13c2c2', resourceCount: 0 }
        ];
        setCategoriesData(defaultCategories);
      }

      // 如果用户已登录，获取用户积分
      if (user) {
        const pointsRes = await points.getUserPoints(user.username);
        if (pointsRes.success) {
          setUserPoints(pointsRes.data.points);
        }
      }

    } catch (error) {
      console.error('加载主页数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async (value) => {
    try {
      setLoading(true);
      if (!value) {
        // 如果搜索词为空，加载所有种子
        const response = await torrents.getTorrents();
        if (response.success) {
          setTorrentsList(response.data.torrents || []);
        }
        return;
      }

      const response = await torrents.searchTorrents(value);
      if (response.success) {
        setTorrentsList(response.data.torrents || []);
      } else {
        messageApi.error('搜索失败');
      }
    } catch (error) {
      console.error('搜索失败:', error);
      messageApi.error('搜索失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCategoryChange = async (value) => {
    try {
      setLoading(true);
      if (!value) {
        // 如果分类为空，加载所有种子
        const response = await torrents.getTorrents();
        if (response.success) {
          setTorrentsList(response.data.torrents || []);
        }
        return;
      }

      const response = await torrents.getTorrentsByCategory(value);
      if (response.success) {
        setTorrentsList(response.data.torrents || []);
      } else {
        messageApi.error('加载分类失败');
      }
    } catch (error) {
      console.error('按分类加载失败:', error);
      messageApi.error('加载分类数据失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInHours = Math.floor((now - time) / (1000 * 60 * 60));

    if (diffInHours < 1) return '刚刚';
    if (diffInHours < 24) return `${diffInHours}小时前`;
    if (diffInHours < 24 * 7) return `${Math.floor(diffInHours / 24)}天前`;
    return time.toLocaleDateString();
  };

  const formatSize = (sizeInBytes) => {
    // 将字节转换为人类可读的大小格式
    const bytes = Number(sizeInBytes);
    if (!bytes || isNaN(bytes) || bytes <= 0) return '0 B';

    // 转换单位：字节 -> KB -> MB -> GB -> TB
    if (bytes >= 1024 * 1024 * 1024 * 1024) {
      return `${(bytes / (1024 * 1024 * 1024 * 1024)).toFixed(1)} TB`;
    } else if (bytes >= 1024 * 1024 * 1024) {
      return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
    } else if (bytes >= 1024 * 1024) {
      return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    } else if (bytes >= 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    } else {
      return `${bytes} B`;
    }
  };

  const quickActions = [
    {
      title: '上传种子',
      icon: <CloudUploadOutlined />,
      color: '#52c41a',
      path: '/upload',
      description: '分享你的资源'
    },

    {
      title: '全球广播',
      icon: <GlobalOutlined />,
      color: '#fa8c16',
      path: '/broadcasts',
      description: '发布求助信息'
    },
    {
      title: '资源分区',
      icon: <DatabaseOutlined />,
      color: '#722ed1',
      path: '/resources',
      description: '浏览分类资源'
    }
  ];

  if (!user || loading) {
    return <div>加载中...</div>;
  }

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto', padding: '24px' }}>
        {/* 欢迎横幅 */}
        <Card style={{ marginBottom: 24, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
          <Row align="middle">
            <Col span={16}>
              <div style={{ color: 'white' }}>
                <Title level={2} style={{ color: 'white', marginBottom: 8 }}>
                  <RocketOutlined /> 欢迎来到星域
                </Title>
                <Paragraph style={{ color: 'rgba(255,255,255,0.8)', fontSize: '16px', marginBottom: 16 }}>
                  一个集种子分享、社区交流、全球广播于一体的私有资源站点
                </Paragraph>
                <Space size="large">
                  <Statistic
                    title={<div style={{ color: 'yellow',fontWeight: 'bold'}}>总种子数</div>}
                    value={torrentsList.length}
                    valueStyle={{ color: 'white' }}
                    prefix={<GiftOutlined />}
                  />
                  <Statistic
                    title={<div style={{ color: 'yellow',fontWeight: 'bold' }}>活跃话题</div>}
                    value={hotTopics.length}
                    valueStyle={{ color: 'white' }}
                    prefix={<TeamOutlined />}
                  />
                  <Statistic
                    title={<div style={{ color: 'yellow' ,fontWeight: 'bold'}}>广播消息</div>}
                    value={latestBroadcasts.length}
                    valueStyle={{ color: 'white' }}
                    prefix={<GlobalOutlined />}
                  />
                </Space>
              </div>
            </Col>
            <Col span={8}>
              {currentUser && userPoints && (
                <Card style={{ background: 'rgba(255,255,255,0.1)', border: 'none' }}>
                  <div style={{ color: 'white', textAlign: 'center' }}>
                    <Avatar size={64} icon={<UserOutlined />} style={{ marginBottom: 16 }} />
                    <Title level={4} style={{ color: 'white', marginBottom: 8 }}>
                      {currentUser.username}
                    </Title>
                    <Row gutter={16}>
                      <Col span={12}>
                      <Statistic
                          title={
                            <div style={{
                              fontWeight: 'bold',
                              color: 'white' 
                                 }}>
                                   魔力值
                                 </div>
                              }
                          value={userPoints.magicValue}
                          valueStyle={{ color: 'white', fontSize: '18px' }}
                        />
                      </Col>
                      <Col span={12}>
                        <Statistic
                          title={
                            <div style={{
                              fontWeight: 'bold',
                              color: 'white'
                                 }}>
                                   星币
                                 </div>
                              }
                          value={userPoints.starCoins}
                          valueStyle={{ color: 'white', fontSize: '18px' }}
                        />
                      </Col>
                    </Row>
                  </div>
                </Card>
              )}
            </Col>
          </Row>
        </Card>

        {/* 快捷操作 */}
        <Card title="快捷操作" style={{ marginBottom: 24 }}>
          <Row gutter={16}>
            {quickActions.map((action, index) => (
              <Col span={6} key={index}>
                <Card
                  hoverable
                  style={{ textAlign: 'center', height: '100%' }}
                  onClick={() => navigate(action.path)}
                >
                  <Avatar
                    size={64}
                    style={{ backgroundColor: action.color, marginBottom: 16 }}
                    icon={action.icon}
                  />
                  <Title level={4} style={{ marginBottom: 8 }}>
                    {action.title}
                  </Title>
                  <Text type="secondary">{action.description}</Text>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>

        <Row gutter={24}>
          {/* 最新种子 */}
          <Col span={12}>
            <Card
              title={
                <span>
                  <GiftOutlined /> 最新种子
                </span>
              }
              extra={
                <Button type="link" onClick={() => navigate('/torrents')}>
                  查看更多
                </Button>
              }
              style={{ marginBottom: 24 }}
            >
              <List
                dataSource={recentTorrents}
                renderItem={torrent => (
                  <List.Item
                    style={{ cursor: 'pointer' }}
                    onClick={() => {
                      console.log('🔗 点击种子跳转:', {
                        id: torrent.id,
                        name: torrent.name,
                        path: `/torrent/${torrent.id}`
                      });
                      navigate(`/torrent/${torrent.id}`);
                    }}
                  >
                    <List.Item.Meta
                      avatar={
                        <Badge count={torrent.qualityScore || 50} style={{ backgroundColor: '#52c41a' }}>
                          <Avatar icon={<GiftOutlined />} style={{ backgroundColor: '#1890ff' }} />
                        </Badge>
                      }
                      title={
                        <div>
                          <Text strong>{torrent.name}</Text>
                          <Tag color="blue" style={{ marginLeft: 8 }}>{torrent.category}</Tag>
                          {/* 促销标签 */}
                          {torrent.promotion && torrent.promotion !== 'none' && (
                            <>
                              {torrent.promotion === 'double_upload' && (
                                <Tag color="green" size="small" style={{ marginLeft: 4 }}>⬆️ 2x上传</Tag>
                              )}
                              {torrent.promotion === 'free_download' && (
                                <Tag color="orange" size="small" style={{ marginLeft: 4 }}>🆓 免费</Tag>
                              )}
                            </>
                          )}
                        </div>
                      }
                      description={
                        <Space split={<Divider type="vertical" />}>
                          <Text type="secondary">{formatSize(torrent.size)}</Text>
                          <Text type="secondary">{formatTime(torrent.uploadTime)}</Text>
                          <Text type="secondary">S: {torrent.seeders || 0}</Text>
                          <Text type="secondary">D: {torrent.downloads || 0}</Text>
                          <Text type="secondary">V: {torrent.views || 0}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>

          {/* 热门话题 */}
          <Col span={12}>
            <Card
              title={
                <span>
                  <TeamOutlined /> 热门话题
                </span>
              }
              extra={
                <Button type="link" onClick={() => navigate('/topics')}>
                  查看更多
                </Button>
              }
              style={{ marginBottom: 24 }}
            >
              <List
                dataSource={hotTopics}
                renderItem={topic => (
                  <List.Item
                    style={{ cursor: 'pointer' }}
                    onClick={() => navigate(`/topics/${topic.topicId || topic.id}`)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<TeamOutlined />} style={{ backgroundColor: '#722ed1' }} />}
                      title={
                        <div>
                          <Text strong>{topic.title || topic.name}</Text>
                          <Tag color="purple" style={{ marginLeft: 8 }}>{topic.category}</Tag>
                        </div>
                      }
                      description={
                        <Space split={<Divider type="vertical" />}>
                          <Text type="secondary">成员: {topic.memberCount || 0}</Text>
                          <Text type="secondary">帖子: {topic.postCount || 0}</Text>
                          <Text type="secondary">创建于: {formatTime(topic.createTime)}</Text>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>

        {/* 最新广播 */}
        <Card
          title={
            <span>
              <GlobalOutlined /> 最新广播
            </span>
          }
          extra={
            <Button type="link" onClick={() => navigate('/broadcasts')}>
              查看更多
            </Button>
          }
          style={{ marginBottom: 24 }}
        >
          <List
            dataSource={latestBroadcasts}
            renderItem={broadcast => (
              <List.Item
                actions={[
                  <Space key="stats">
                    <Tooltip title="浏览量">
                      <span><EyeOutlined /> {broadcast.viewCount || 0}</span>
                    </Tooltip>
                    <Tooltip title="点赞数">
                      <span><LikeOutlined /> {broadcast.likeCount || 0}</span>
                    </Tooltip>
                  </Space>
                ]}
              >
                <List.Item.Meta
                  avatar={<Avatar icon={<GlobalOutlined />} style={{ backgroundColor: '#fa8c16' }} />}
                  title={
                    <div>
                      <Text strong>{broadcast.title}</Text>
                      <Tag color="orange" style={{ marginLeft: 8 }}>
                        {broadcast.type === 'seed_request' ? '种子求助' :
                          broadcast.type === 'resource_share' ? '资源分享' : '公告通知'}
                      </Tag>
                    </div>
                  }
                  description={
                    <div>
                      <Paragraph ellipsis={{ rows: 1 }}>{broadcast.content}</Paragraph>
                      <Space>
                        <Text type="secondary">发布者: {broadcast.username}</Text>
                        <Text type="secondary">{formatTime(broadcast.createTime)}</Text>
                      </Space>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </Card>

        {/* 分区统计 */}
        <Card title={<span><DatabaseOutlined /> 分区概览</span>}>
          <Row gutter={16}>
            {categoriesData.slice(0, 6).map((category, index) => (
              <Col span={4} key={index}>
                <Card
                  hoverable
                  size="small"
                  style={{ textAlign: 'center' }}
                  onClick={() => navigate(`/resources?category=${encodeURIComponent(category.name)}`)}
                >
                  <Avatar
                    size={48}
                    style={{ backgroundColor: category.color, marginBottom: 8 }}
                    icon={<DatabaseOutlined />}
                  />
                  <Title level={5} style={{ margin: 0 }}>
                    {category.name}
                  </Title>
                  <Text type="secondary">
                    {category.resourceCount || 0} 个资源
                  </Text>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>
      </div>
    </div>
  );
};

export default Home; 